package org.jeecg.modules.demo.huibaozhibiaodaibanbiao.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.huibaojilubiao.entity.Huibaojilubiao;
import org.jeecg.modules.demo.huibaojilubiao.service.IHuibaojilubiaoService;
import org.jeecg.modules.demo.huibaozhibiaodaibanbiao.entity.HuibaoDto;
import org.jeecg.modules.demo.huibaozhibiaodaibanbiao.entity.Huibaozhibiaodaibanbiao;
import org.jeecg.modules.demo.huibaozhibiaodaibanbiao.service.IHuibaozhibiaodaibanbiaoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.zhibiaobiao.entity.Zhibiaobiao;
import org.jeecg.modules.demo.zhibiaobiao.service.IZhibiaobiaoService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
 /**
 * @Description: 汇报指标待办表
 * @Author: jeecg-boot
 * @Date:   2025-09-24
 * @Version: V1.0
 */
@Tag(name="汇报指标待办表")
@RestController
@RequestMapping("/huibaozhibiaodaibanbiao/huibaozhibiaodaibanbiao")
@Slf4j
public class HuibaozhibiaodaibanbiaoController extends JeecgController<Huibaozhibiaodaibanbiao, IHuibaozhibiaodaibanbiaoService> {
	@Autowired
	private IHuibaozhibiaodaibanbiaoService huibaozhibiaodaibanbiaoService;
	@Autowired
	private IZhibiaobiaoService zhibiaobiaoService;
	@Autowired
	private IHuibaojilubiaoService huibaojilubiaoService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ISysDepartService sysDepartService;

	/**
	 * 分页列表查询
	 *
	 * @param huibaozhibiaodaibanbiao
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "汇报指标待办表-分页列表查询")
//	@Operation(summary="汇报指标待办表-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<IPage<Huibaozhibiaodaibanbiao>> queryPageList(Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//
//
//        QueryWrapper<Huibaozhibiaodaibanbiao> queryWrapper = QueryGenerator.initQueryWrapper(huibaozhibiaodaibanbiao, req.getParameterMap());
//		Page<Huibaozhibiaodaibanbiao> page = new Page<Huibaozhibiaodaibanbiao>(pageNo, pageSize);
//		IPage<Huibaozhibiaodaibanbiao> pageList = huibaozhibiaodaibanbiaoService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}
	//汇报部门只看见自己部门的项目
	@GetMapping(value = "/list")
	public Result<IPage<HuibaoDto>> list(Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao,
										@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
										HttpServletRequest  req){
		//获取登录用户的角色id
		LoginUser User = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departId = User.getDepartIds();
		//获取角色id
		String userId = User.getId();
		QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
		qw.eq("user_id", userId);
		SysUserRole sysUserRole = sysUserRoleService.getOne(qw);
		String sysRoleId = sysUserRole.getRoleId();

		//再去汇报指标表查询
		List<HuibaoDto> dto = new ArrayList<>();
		Page<Huibaozhibiaodaibanbiao> page = new Page<Huibaozhibiaodaibanbiao>(pageNo, pageSize);
		QueryWrapper<Huibaozhibiaodaibanbiao> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("zerenbumen",departId);
		IPage<Huibaozhibiaodaibanbiao> pageList = huibaozhibiaodaibanbiaoService.page(page, queryWrapper);
		IPage<HuibaoDto> pageDto = new Page<>();
		List<Huibaozhibiaodaibanbiao> list = pageList.getRecords();
		//角色判断
		if(sysRoleId.equals("1970852625298092033")){
			for(int i = 0;i<list.size();i++){
				HuibaoDto huibaoDto = new HuibaoDto();
				huibaoDto.setId(list.get(i).getId());
				huibaoDto.setZhibiaoid(list.get(i).getZhibiaoid());
				huibaoDto.setZhuangtai(list.get(i).getZhuangtai());
				huibaoDto.setHuibaoyuefen(list.get(i).getHuibaoyuefen());
				QueryWrapper<Zhibiaobiao > queryWrapper2 = new QueryWrapper<>();
				queryWrapper2.eq("id",list.get(i).getZhibiaoid());

//			zhibiaobiaoService.getById(list.get(i).getZhibiaoid())

				String gongzuoneirong = zhibiaobiaoService.getById(list.get(i).getZhibiaoid()).getKaohezhibiao();
				String peihebumen = zhibiaobiaoService.getById(list.get(i).getZhibiaoid()).getPeihebumen();
				huibaoDto.setGongzuoneirong(gongzuoneirong);
				huibaoDto.setPeihebumen(peihebumen);
				String zhuangtai = list.get(i).getZhuangtai();
				if(zhuangtai.equals("待汇报") || zhuangtai.equals("待审核") || zhuangtai.equals("已完成")){
					QueryWrapper<Huibaojilubiao> queryWrapper3 = new QueryWrapper<>();
					queryWrapper3.eq("huibaozhibiaoid",list.get(i).getId());
					queryWrapper3.orderByDesc("create_time");
					queryWrapper3.last("limit 1");
					//需要修改
					List<Huibaojilubiao> huibaojilubiaoList = huibaojilubiaoService.list(queryWrapper3);
					for(Huibaojilubiao huibaojilubiao:huibaojilubiaoList){
						huibaoDto.setJieduanchengguo(huibaojilubiao.getJieduanchengguo());
						huibaoDto.setWanchengjindu(huibaojilubiao.getWanchengjindu());
						huibaoDto.setShifouyujing(huibaojilubiao.getShifouyujing());
					}
				}

				dto.add(huibaoDto);
			}
		}else if(sysRoleId.equals("1970852557262286850")){
			QueryWrapper<SysDepart> queryWrapper1 = new QueryWrapper<>();
			queryWrapper1.eq("parent_id",departId);
			List<SysDepart> sysDeparts = sysDepartService.list(queryWrapper1);
			for(int i =0;i<sysDeparts.size();i++){
				String fenguandepartId = sysDeparts.get(i).getId();
				System.out.println("主管部门id"+fenguandepartId);
				QueryWrapper<Huibaozhibiaodaibanbiao> queryWrapper2 = new QueryWrapper<>();
				queryWrapper2.eq("zerenbumen",fenguandepartId);
				queryWrapper2.eq("zhuangtai","待审核");
				List<Huibaozhibiaodaibanbiao> list2 = huibaozhibiaodaibanbiaoService.list(queryWrapper2);
				for(int j = 0;j<list2.size();j++){
					HuibaoDto huibaoDto = new HuibaoDto();
					huibaoDto.setId(list2.get(j).getId());
					huibaoDto.setZhibiaoid(list2.get(j).getZhibiaoid());
					huibaoDto.setZhuangtai(list2.get(j).getZhuangtai());
					huibaoDto.setHuibaoyuefen(list2.get(j).getHuibaoyuefen());
					QueryWrapper<Zhibiaobiao > queryWrapper3 = new QueryWrapper<>();
					queryWrapper3.eq("id",list2.get(j).getZhibiaoid());
					String gongzuoneirong = zhibiaobiaoService.getById(list2.get(j).getZhibiaoid()).getKaohezhibiao();
					huibaoDto.setGongzuoneirong(gongzuoneirong);
					String peihebumen = zhibiaobiaoService.getById(list2.get(j).getZhibiaoid()).getPeihebumen();
					huibaoDto.setPeihebumen(peihebumen);
					System.out.println("qqqq"+list2.get(j).getId());
					QueryWrapper<Huibaojilubiao> queryWrapper4 = new QueryWrapper<>();
					queryWrapper4.eq("huibaozhibiaoid",list2.get(j).getId());
					queryWrapper4.orderByDesc("create_time");
					queryWrapper4.last("limit 1");
					Huibaojilubiao huibaojilubiao = huibaojilubiaoService.getOne(queryWrapper4);
					if(huibaojilubiao != null){
						String jieduanchenguo = huibaojilubiao.getJieduanchengguo();
						huibaoDto.setWanchengjindu(jieduanchenguo);
						String jinzhanqingkuang = huibaojilubiao.getWanchengjindu();
						huibaoDto.setWanchengjindu(jinzhanqingkuang);
						String shifouyujin = huibaojilubiao.getShifouyujing();
						huibaoDto.setShifouyujing(shifouyujin);
					}else{
						break;
					}
					dto.add(huibaoDto);
				}
			}
		}else{
			return Result.error("没有权限");
		}
		pageDto.setRecords(dto);
		return Result.OK(pageDto);
	}

	//汇报
	@PostMapping(value = "/huibao")
	public Result<String> huibao(@RequestBody HuibaoDto huibaoDto) {
		//部长id   1970852625298092033
		//获取登录用户的角色id
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userId = user.getId();
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		SysUserRole sysUserRole = sysUserRoleService.getOne(queryWrapper);
		String sysRoleId = sysUserRole.getRoleId();
		if (huibaoDto.getZhuangtai().equals("待汇报")) {
			if (sysRoleId.equals("1970852625298092033")) {
				//点击某条记录进行汇报，获取该条记录的id，根据前端传来的数据插入huibaojilubiao表并保存
				Huibaojilubiao huibaojilubiao = new Huibaojilubiao();
				String tijiaozhuangtai = huibaoDto.getTijiaozhuangtai();
				if (tijiaozhuangtai.equals("暂存")) {
					huibaojilubiao.setHuibaozhibiaoid(huibaoDto.getId());
					huibaojilubiao.setJieduanchengguo(huibaoDto.getJieduanchengguo());
					huibaojilubiao.setWanchengjindu(huibaoDto.getWanchengjindu());
					huibaojilubiao.setShifouyujing(huibaoDto.getShifouyujing());
					huibaojilubiao.setZhuangtai("暂存");
					huibaojilubiaoService.save(huibaojilubiao);
				} else if (tijiaozhuangtai.equals("提交")) {
					huibaojilubiao.setHuibaozhibiaoid(huibaoDto.getId());
					huibaojilubiao.setJieduanchengguo(huibaoDto.getJieduanchengguo());
					huibaojilubiao.setWanchengjindu(huibaoDto.getWanchengjindu());
					huibaojilubiao.setShifouyujing(huibaoDto.getShifouyujing());
					huibaojilubiao.setZhuangtai("提交");
					huibaojilubiaoService.save(huibaojilubiao);
					Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao = huibaozhibiaodaibanbiaoService.getById(huibaoDto.getId());
					huibaozhibiaodaibanbiao.setZhuangtai("待审核");
					huibaozhibiaodaibanbiaoService.updateById(huibaozhibiaodaibanbiao);
					return Result.OK("汇报成功");
				} else {
					return Result.error("请选择提交或暂存");
				}
			}else{
				return Result.error("您没有权限执行此操作");
			}
		} else {
			return Result.error("该记录已经完成汇报");
		}
		return Result.OK("汇报成功");
	}

	//展示暂存汇报记录
	@PostMapping(value = "huibaoList")
	public Result<Huibaojilubiao> huibaoList(@RequestBody HuibaoDto huibaoDto){
		String huibaoid = huibaoDto.getId();
		QueryWrapper<Huibaojilubiao> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("huibaozhibiaoid",huibaoid);
		queryWrapper.orderByDesc("create_time");
		queryWrapper.last("limit 1");
		Huibaojilubiao huibaojilubiao = huibaojilubiaoService.getOne(queryWrapper);
		if(huibaojilubiao != null){
			return Result.OK(huibaojilubiao);
		}
		return Result.OK(null);
	}



	//审核展示列表
//	@GetMapping(value = "/shenheList")
//	public Result<List<HuibaoDto>> shenheList(){
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		String departId = user.getDepartIds();
//		return Result.OK(dto);
//	}

	//审核
	@PostMapping(value="shenhe")
	public Result<String> shenhe(@RequestBody HuibaoDto huibaoDto){
		//获取登录用户用户id
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userId = user.getId();
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id",userId);
		SysUserRole sysUserRole = sysUserRoleService.getOne(queryWrapper);
		String roleId = sysUserRole.getRoleId();
		if(roleId.equals("1970852557262286850")){
			String shifoutongguo = huibaoDto.getShifoutongguo();
			String id = huibaoDto.getId();
			if(shifoutongguo.equals("true")){
				QueryWrapper<Huibaozhibiaodaibanbiao> queryWrapper1 = new QueryWrapper<>();
				queryWrapper1.eq("id",id);
				Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao = huibaozhibiaodaibanbiaoService.getOne(queryWrapper1);
				huibaozhibiaodaibanbiao.setZhuangtai("已完成");
				huibaozhibiaodaibanbiaoService.updateById(huibaozhibiaodaibanbiao);
				return Result.OK("审核成功");
			} else if (shifoutongguo.equals("false")) {
				QueryWrapper<Huibaozhibiaodaibanbiao> queryWrapper2 = new QueryWrapper<>();
				queryWrapper2.eq("id",id);
				Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao = huibaozhibiaodaibanbiaoService.getOne(queryWrapper2);
				huibaozhibiaodaibanbiao.setZhuangtai("待审核");
				huibaozhibiaodaibanbiaoService.updateById(huibaozhibiaodaibanbiao);
				return Result.OK("审核成功");
			}
			return Result.error("请选择通过或未通过");
		}else{
			return Result.error("您没有权限执行此操作");
		}
	}

	/**
	 *   添加
	 *
	 * @param huibaozhibiaodaibanbiao
	 * @return
	 */
	@AutoLog(value = "汇报指标待办表-添加")
	@Operation(summary="汇报指标待办表-添加")
	@RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao) {
		huibaozhibiaodaibanbiaoService.save(huibaozhibiaodaibanbiao);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param huibaozhibiaodaibanbiao
	 * @return
	 */
	@AutoLog(value = "汇报指标待办表-编辑")
	@Operation(summary="汇报指标待办表-编辑")
	@RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao) {
		huibaozhibiaodaibanbiaoService.updateById(huibaozhibiaodaibanbiao);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "汇报指标待办表-通过id删除")
	@Operation(summary="汇报指标待办表-通过id删除")
	@RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		huibaozhibiaodaibanbiaoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "汇报指标待办表-批量删除")
	@Operation(summary="汇报指标待办表-批量删除")
	@RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.huibaozhibiaodaibanbiaoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "汇报指标待办表-通过id查询")
	@Operation(summary="汇报指标待办表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Huibaozhibiaodaibanbiao> queryById(@RequestParam(name="id",required=true) String id) {
		Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao = huibaozhibiaodaibanbiaoService.getById(id);
		if(huibaozhibiaodaibanbiao==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(huibaozhibiaodaibanbiao);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param huibaozhibiaodaibanbiao
    */
    @RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Huibaozhibiaodaibanbiao huibaozhibiaodaibanbiao) {
        return super.exportXls(request, huibaozhibiaodaibanbiao, Huibaozhibiaodaibanbiao.class, "汇报指标待办表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("huibaozhibiaodaibanbiao:x_huibaozhibiaodaibanbiao:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Huibaozhibiaodaibanbiao.class);
    }

}
